<template>
  <div v-loading="fullscreenLoading" class="app-container">
    <el-row>
      <el-col :span="4">
        <!-- <el-input v-model="form.boxId" style="width: 240px" @input="boxIdChange" placeholder="箱号" /> -->
        <el-input v-model="form.boxId" style="width: 200px" @input="boxIdChange2" placeholder="外箱号(可粘贴Excel整列)" />
      </el-col>
      <el-col :span="4">
        <!-- <el-input v-model="form.boxId" style="width: 240px" @input="boxIdChange" placeholder="箱号" /> -->
        <el-input v-model="form.receivedflag" style="width: 200px" @input="boxIdChange2" placeholder="ASN" />
      </el-col>
      <el-col :span="4">
        <el-input v-model="form.fgcode" style="width: 200px" @input="boxIdChange2" placeholder="型号" />
      </el-col>
      <!-- <el-col :span="2">
        <el-text class="mx-1" type="primary" style="line-height: 32px">{{ storeDataList.length }} 条</el-text>
      </el-col> -->
      <el-col :span="8">
        <div class="block">
          <el-date-picker
            v-model="dateRange"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :default-time="defaultTime1"
            @change="onDateChange"
            unlink-panels="false" />
        </div>
      </el-col>

      <el-col :span="2">
        <div class="mb-4">
          <el-button type="primary" :icon="Search" @click="submitForm">查询</el-button>
        </div>
      </el-col>
      <!-- <el-col :span="2">
        <el-button v-loading="exportLoading" type="warning" plain icon="download" @click="exportToExcel2()">导出</el-button>
      </el-col> -->
      <el-col :span="2">
        <el-dropdown @command="handleCommand">
          <el-button type="primary" :icon="Edit" circle />
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="export">导出数据</el-dropdown-item>
              <el-dropdown-item command="mark_as_thrown">标记已抛</el-dropdown-item>
              <el-dropdown-item command="mark_as_not_thrown">标记未抛</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-col>
    </el-row>
    <el-row style="margin-top: 8px">
      <el-table :data="storeDataList" border height="600" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="superprocessgroupname" label="外箱号" align="center" />
        <el-table-column prop="receiveflag" label="已上抛客户系统" align="center" />
        <el-table-column prop="receivedflag" label="ASN单号" align="center" />
        <el-table-column prop="fgcode" label="型号" align="center" />
        <el-table-column prop="throwncustomertime" label="上抛时间" align="center" />
      </el-table>
    </el-row>
    <el-row class="pagination-container">
      <el-pagination
        @size-change="sizeChange"
        @current-change="currentChange"
        :current-page="page"
        :page-sizes="[50, 100, 200, 500]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total" />
    </el-row>

    <el-drawer v-model="drawer" title="I am the title" :with-header="true">
      <span>{{ drawerMessage }}</span>
    </el-drawer>
  </div>
</template>


<script setup name="ASN">
import { selectlist, updatemarkThrown, updatemarknotThrown } from '@/api/infoSerch/ASNSerch'
import * as XLSX from 'xlsx'
import _ from 'lodash'
import { Edit } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
const dateRange = ref([])
const defaultTime1 = new Date(2000, 1, 1, 12, 0, 0)
const { proxy } = getCurrentInstance()
const drawer = ref(false)
const drawerMessage = ref('')
const fullscreenLoading = ref(false)

const total = ref(0)
const pageSize = ref(100)
const page = ref(1)

const state = reactive({
  form: {
    boxId: '',
    fgcode: '',
    receivedflag: '', //ASN单号
    startTime: '',
    endTime: ''
  },
  storeDataList: [], //存当前页数据
  storeDataListAll: [], //所有页数据
  retInfo: {},
  retMessage: '',
  exportLoading: false,
  selectedRows: [] //勾选行
})

const { form, storeDataList, storeDataListAll, retMessage, exportLoading, selectedRows } = toRefs(state)

//查询按钮
function submitForm() {
  fullscreenLoading.value = true
  onDateChange(dateRange.value)
  selectlist({ ...form.value }).then((res) => {
    storeDataListAll.value = res.data
    //console.log(res.data.data)
    retMessage.value = res.msg
    total.value = res.data.length
    getTableData()
    fullscreenLoading.value = false
  })
}
//开始时间和结束时间在数组里
const onDateChange = (value) => {
  if (value && value.length === 2) {
    form.value.startTime = new Date(value[0].getTime() + 28800000)
    form.value.endTime = new Date(value[1].getTime() + 28800000)
  } else {
    form.value.startTime = null
    form.value.endTime = null
  }
}

function sizeChange(val) {
  pageSize.value = val
  page.value = 1
  getTableData()
}
function getTableData() {
  storeDataList.value = storeDataListAll.value.slice((page.value - 1) * pageSize.value, page.value * pageSize.value)
}
function currentChange(val) {
  page.value = val
  getTableData()
}

//编辑中的三个方法
function handleCommand(command) {
  if (command === 'export') {
    exportToExcel2()
  } else if (command === 'mark_as_thrown') {
    if (selectedRows.value.length > 0) {
      markThrown()
    } else {
      drawer.value = true
      drawerMessage.value = '请先勾选箱号后，再执行【标记已抛】'
    }
  } else if (command === 'mark_as_not_thrown') {
    if (selectedRows.value.length > 0) {
      marknotThrown()
    } else {
      drawer.value = true
      drawerMessage.value = '请先勾选箱号后，再执行【标记未抛】'
    }
  }
}

//标记未抛 reciveflag >2
function marknotThrown() {
  updatemarknotThrown(selectedRows.value)
    .then((response) => {
      if (response.code === 200) {
        proxy.$message({
          message: '标记未抛成功',
          type: 'success',
          duration: 2000 // 1秒后自动消失
        })
        submitForm()
      } else {
        proxy.$message({
          message: '标记未抛失败',
          type: 'error',
          duration: 2000 // 1秒后自动消失
        })
      }
    })
    .catch((error) => {
      proxy.$message({
        message: '标记未抛时发生错误',
        type: 'error',
        duration: 2000 // 1秒后自动消失
      })
    })
}
//标记已抛 reciveflag == 2
function markThrown() {
  updatemarkThrown(selectedRows.value)
    .then((response) => {
      if (response.code === 200) {
        proxy.$message({
          message: '标记已抛成功',
          type: 'success',
          duration: 2000 // 1秒后自动消失
        })
        submitForm()
      } else {
        proxy.$message({
          message: '标记已抛失败',
          type: 'error',
          duration: 2000 // 1秒后自动消失
        })
      }
    })
    .catch((error) => {
      proxy.$message({
        message: '标记未抛时发生错误',
        type: 'error',
        duration: 2000 // 1秒后自动消失
      })
    })
}

// 处理勾选状态变化
function handleSelectionChange(selection) {
  selectedRows.value = selection
}

// 快速导出所有数据到excel表格，仅前端一个方法
function exportToExcel2() {
  const data = storeDataListAll.value
  //const fileNamePrefix = form.value.boxId
  exportLoading.value = true
  if (data.length === 0) {
    drawer.value = true // 数据为空，显示抽屉并设置消息
    drawerMessage.value = '嗨，没有数据可以导出'
    exportLoading.value = false
  } else {
    exportLoading.value = false
  }
  const now = new Date()
  const fileNameSuffix = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now
    .getDate()
    .toString()
    .padStart(2, '0')}_${now.getHours().toString().padStart(2, '0')}-${now.getMinutes().toString().padStart(2, '0')}-${now
    .getSeconds()
    .toString()
    .padStart(2, '0')}`
  // const fileName = `${fileNamePrefix}_${fileNameSuffix}.xlsx`
  const fileName = `${fileNameSuffix}.xlsx`
  const headers = Object.keys(data[0]).map((key) => ({
    header: key, // 将字段名作为标题
    key: key // key与字段名相同
  }))
  headers.forEach((headerObj) => {
    const customHeaders = {
      superprocessgroupname: '外箱号',
      receiveflag: '上抛客户系统',
      receivedflag: 'ASN单号',
      fgcode: '型号',
      throwncustomertime: '上抛时间'
    }
    if (customHeaders[headerObj.key]) {
      headerObj.header = customHeaders[headerObj.key]
    }
  })
  const sheetData = [headers.map((h) => h.header)] // 第一行是标题
  sheetData.push(...data.map((item) => headers.map((h) => item[h.key])))
  const worksheet = XLSX.utils.aoa_to_sheet(sheetData)

  //const worksheet = XLSX.utils.json_to_sheet(data)
  const workbook = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')
  const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' })
  const blob = new Blob([excelBuffer], { type: 'application/octet-stream' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = fileName
  a.click()
  URL.revokeObjectURL(url)
  exportLoading.value = false
}
</script>
<style scoped>
.pagination-container {
  display: flex;
  justify-content: right;
}
</style>

